#include "chatserver.hpp"
#include "json.hpp"
#include "chatservice.hpp"
#include "CommonConnectionPool.hpp"

#include <functional>

using namespace std;
using namespace placeholders;
using json = nlohmann::json;

ChatServer::ChatServer(
    EventLoop *loop,
    const InetAddress &addr,
    const std::string &name) : _server(loop, addr, name),
                               _loop(loop)
{
    // 注册各种回调参数
    _server.setConnectionCallback(bind(&ChatServer::onConnection, this, _1));
    _server.setMessageCallback(bind(&ChatServer::onMessage, this, _1, _2, _3));

    // 线程安全地定义数据库连接池(饥汉模式)
    ConnectionPool::getConnectionPool();
}

ChatServer::~ChatServer(){};

void ChatServer::onConnection(const TcpConnectionPtr &conn)
{
    // 断开连接时，调用回调
    if (!conn->connected())
    {
        ChatService::instance()->onErrorDisconnect(conn);
        conn->shutdown();
    }
    // 建立连接时的回调
    else
    {
    }
}
void ChatServer::onMessage(const TcpConnectionPtr &conn, Buffer *buffer, Timestamp time)
{
    // 接收缓冲区中内容
    string buf = buffer->retrieveAllAsString();
    // json反序列化
    json js = json::parse(buf);
    // 执行消息ID对应的handler
    ChatService::instance()->getHandler(js["msgid"].get<int>())(
        conn,
        js,
        time);
}

void ChatServer::start()
{
    _server.start();
}
